let VshaderSource =
    'attribute vec4 a_Position;\n' +
    'uniform mat4 u_ModelMatrix;\n' +
    'void main(){\n' +
    '   gl_Position = u_ModelMatrix * a_Position;\n' +
    '}\n'

let FshaderSource =
    'void main() {\n' +
    '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
    '}\n';

let ANGLE_STEP = 45.0

function main(ANGLE = 10) {
    const canvas = document.getElementById('webgl')
    const gl = getWebGLContext(canvas)
    if (!initShaders(gl, VshaderSource, FshaderSource)) {
        console.log('init shader error');
    }

    let n = initVertexBuffers(gl)

    let curAngle = 0.0

    let modelMatrix = new Matrix4()
    let u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix')


    let tick = () => {
        curAngle = animate(curAngle)
        draw(gl, n, curAngle, modelMatrix, u_ModelMatrix)
        requestAnimationFrame(tick)
    }
    tick()

    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.drawArrays(gl.TRIANGLES, 0, n);
}

function initVertexBuffers(gl) {
    let vertices = new Float32Array([
        0.0, 0.5,
        -0.5, -0.5,
        0.5, -0.5
    ])
    let n = 3

    let vertexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

    let a_Position = gl.getAttribLocation(gl.program, 'a_Position')
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
    gl.enableVertexAttribArray(a_Position)
    return n
}

function draw(gl, n, curAngle, modelMatrix, u_ModelMatrix) {
    modelMatrix.setRotate(curAngle, 0, 0, 1)
    modelMatrix.translate(0.5,0,0)
    gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements)
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.drawArrays(gl.TRIANGLES, 0, n)
}

let g_last = Date.now()
function animate(angle) {
    let now = Date.now()
    let elapsed = now - g_last
    g_last = now

    let newAngle = angle + (ANGLE_STEP * elapsed) / 1000.0
    return newAngle %= 360
}